﻿using Coldairarrow.Util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Util;

namespace API.Controllers
{
    [Route("/api/ydl/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class BaseController : ControllerBase
    {
        // 用户ID 
        protected string CurrentUserId => User.FindFirstValue("userid") ?? "";
        // 手机号 
        protected string CurrentPhone => User.FindFirstValue("phone") ?? "";// 手机号 
        public BaseController()
        {

        }
        /// <summary>
        /// 获取当前Token
        /// </summary>
        /// <returns></returns>
        protected string GetCurrentToken()
        {
            var authorizationHeader = Request.Headers["Authorization"].FirstOrDefault();
            if (!string.IsNullOrEmpty(authorizationHeader) && authorizationHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
            {
                return authorizationHeader.Substring("Bearer ".Length).Trim();
            }

            return null;
        }
        /// <summary>
        /// 初始化实体
        /// </summary>
        /// <param name="obj"></param>
        protected void InitEntity(object obj)
        {
            // 获取当前 Id 的值
            var currentId = obj.GetPropertyValue("Id");

            // 检查 Id 是否为空
            if (currentId == null || string.IsNullOrEmpty(currentId.ToString()))
            {
                // 如果 Id 为空，则设置新的 Id
                obj.SetPropertyValue("Id", IdHelper.GetId());
            }
            //if (obj.ContainsProperty("Id"))
            //    obj.SetPropertyValue("Id", IdHelper.GetId());
            if (obj.ContainsProperty("CreateTime"))
                obj.SetPropertyValue("CreateTime", DateTime.Now);
            if (obj.ContainsProperty("CreateId"))
                obj.SetPropertyValue("CreateId", CurrentUserId);
            if (obj.ContainsProperty("UpdateTime"))
                obj.SetPropertyValue("UpdateTime", DateTime.Now);
            if (obj.ContainsProperty("UpdateId"))
                obj.SetPropertyValue("UpdateId", CurrentUserId);
        }
    }
}
